package com.example.todosync.controller;

import com.example.todosync.service.StorageService;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.*;

@RestController
@RequestMapping("/sync")
public class TodoController {
    private final StorageService storage;

    public TodoController(StorageService storage) {
        this.storage = storage;
    }

    @GetMapping
    public Map<String, Object> getTodos(Principal principal) {
        String user = principal.getName();
        List<JsonNode> items = storage.readItems(user);
        Map<String, Object> resp = new HashMap<>();
        resp.put("items", items);
        return resp;
    }

    @PostMapping
    public ResponseEntity<?> postTodos(Principal principal, @RequestBody JsonNode body) {
        String user = principal.getName();
        try {
            List<JsonNode> items = new ArrayList<>();
            if (body.isArray()) {
                body.forEach(items::add);
            } else {
                JsonNode arr = body.path("items");
                if (arr.isArray()) arr.forEach(items::add);
            }
            storage.writeItems(user, items);
            Map<String, Object> resp = new HashMap<>();
            resp.put("ok", true);
            resp.put("count", items.size());
            return ResponseEntity.ok(resp);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Collections.singletonMap("error", e.getMessage()));
        }
    }
}